const cloud = require('wx-server-sdk');
const { notifyOrderToStaff } = require('./messageNotifyService');
const { printTicket } = require('./PrintService');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV, // 使用当前环境
});

const db = cloud.database();
const _ = db.command; // 初始化数据库命令对象


/**
 * 支付成功回调服务
 * @async
 * @function paySuccessCallback
 * @param {Object} request - 请求对象
 * @param {string} request.orderId - 订单ID
 * @returns {Promise<Object>} 返回处理结果
 * @throws {Error} 当订单不存在时抛出错误
 * @description 
 * 1. 根据订单ID查询订单信息
 * 2. 根据产品类型更新订单状态为"已支付"并设置对应的处理状态
 * 3. 更新优惠券状态（如果存在）
 * 4. 更新砍价记录状态（如果存在）
 * 5. 通知工作人员处理订单
 * 成功时返回200状态码，失败时返回500状态码及错误信息
 */
async function paySuccessCallback(request) {
  try {
    const { orderId } = request; // 获取前端传递的 orderId、couponId 和 participantId

    // 1. 查询订单信息
    console.log(`[paySuccessCallback] 查询订单信息: orderId=${orderId}`);
    const orderResult = await db.collection('order').where({
      order_id: orderId
    }).get();

    if (!orderResult.data.length) {
      console.error(`[paySuccessCallback] 订单不存在: orderId=${orderId}`);
      throw new Error('Order not found');
    }

    const orderData = orderResult.data[0];
    console.log(`[paySuccessCallback] 订单信息获取成功: ${JSON.stringify(orderData)}`);

    // 2. 更新订单状态
    let targetStatus = '-';
    const productId = orderData.order_item.product_id;
    if (productId === 'PPrintBlackAndWhite') {
      targetStatus = '待打印';
    }
    else if (productId === 'PPacakgePickUp') {
      targetStatus = '待取快递';
    }
    else if (productId === 'PWashShoes'||productId === 'PWashClothes') {
      targetStatus = '待取货';
    }    else if (productId === 'PPaoTui'){
      targetStatus = '待接单';
    }
    else if (productId === 'PSnackPickup'){
      targetStatus = '待配送';
    }
    await db.collection('order').doc(orderData._id).update({
      data: {
        order_status: '已支付',
        process_status: targetStatus,
        update_ts: new Date() // 更新时间戳
      }
    });
    console.log(`[paySuccessCallback] 订单状态已更新为已支付，处理状态: ${targetStatus}，orderId=${orderId}`);

    // 3. 更新优惠券状态（如果 couponId 存在）
    try {
      console.log(`[paySuccessCallback] 尝试更新优惠券状态: coupon_record_id=${orderResult.data[0].coupon_record_id}`);
      await updateCouponStatus(orderResult.data[0].coupon_record_id);
      console.log(`[paySuccessCallback] 优惠券状态更新成功: coupon_record_id=${orderResult.data[0].coupon_record_id}`);
    } catch (err) {
      console.error('[paySuccessCallback] 更新优惠券状态失败:', err.message);
      console.error('Stack:', err.stack || '无堆栈信息');
    }

    // 4. 更新砍价记录状态（如果 participantId 存在）
    try {
      console.log(`[paySuccessCallback] 尝试更新砍价记录: participant_id=${orderResult.data[0].participant_id}`);
      await updateBargainRecord(orderResult.data[0].participant_id);
      console.log(`[paySuccessCallback] 砍价记录状态更新成功: participant_id=${orderResult.data[0].participant_id}`);
    } catch (err) {
      console.error('[paySuccessCallback] 更新砍价记录状态失败:', err.message);
      console.error('Stack:', err.stack || '无堆栈信息');
    }

    // 5. 处理零食订单库存扣减（如果是零食订单）
    try {
      if (productId === 'PSnackPickup' && orderData.snacks_items && orderData.snacks_items.length > 0) {
        console.log(`[paySuccessCallback] 开始处理零食库存扣减: orderId=${orderId}`);
        // 获取楼栋信息进行库存扣减
        const buildingCode = orderData.delivery_address?.building_code || orderData.address?.schoolCode;
        await updateSnackStock(orderData.snacks_items, orderData.address.schoolCode, buildingCode);
        console.log(`[paySuccessCallback] 零食库存扣减成功: orderId=${orderId}`);
      }
    } catch (err) {
      console.error('[paySuccessCallback] 零食库存扣减失败:', err.message);
      console.error('Stack:', err.stack || '无堆栈信息');
    }

    let notifyOrderRequest = {orderId: orderId}
    try {
      console.log(`[paySuccessCallback] 通知员工处理订单: orderId=${orderId}`);
      await notifyOrderToStaff(notifyOrderRequest);
      console.log(`[paySuccessCallback] 通知员工成功: orderId=${orderId}`);
    } catch (err) {
      console.error('[paySuccessCallback] 通知员工失败:', err.message);
      console.error('Stack:', err.stack || '无堆栈信息');
    }
    // try {
    //   let printTicketRequest = {orderId: orderId,times:1};
    //   console.log(`[paySuccessCallback] 打印小票: ${JSON.stringify(printTicketRequest)}`);
    //   await printTicket(printTicketRequest);
    //   console.log(`[paySuccessCallback] 打印小票成功: orderId=${orderId}`);
    // } catch (err) {
    //   console.error('[paySuccessCallback] 打印小票失败:', err.message);
    //   console.error('Stack:', err.stack || '无堆栈信息');
    // }

    // 返回成功结果
    console.log(`[paySuccessCallback] 处理完成: orderId=${orderId}`);
    return {
      code: 200,
      message: 'success',
      data: null
    };
  } catch (error) {
    console.error("[paySuccessCallback] Error:", error.stack || error);
    return {
      code: 500,
      message: "Error processing request",
      error: error.stack || error.message
    };
  }
}

async function paoTuiPaySuccessCallback(request) {
  try {
    const { orderId } = request; // 获取前端传递的 orderId、couponId 和 participantId

    // 1. 查询订单信息
    console.log(`[paySuccessCallback] 查询订单信息: orderId=${orderId}`);
    const orderResult = await db.collection('order').where({
      order_id: orderId
    }).get();

    if (!orderResult.data.length) {
      console.error(`[paySuccessCallback] 订单不存在: orderId=${orderId}`);
      throw new Error('Order not found');
    }

    const orderData = orderResult.data[0];
    console.log(`[paySuccessCallback] 订单信息获取成功: ${JSON.stringify(orderData)}`);

    // 2. 更新订单状态
    let targetStatus = '待接单';
    await db.collection('order').doc(orderData._id).update({
      data: {
        order_status: '已支付',
        process_status: targetStatus,
        update_ts: new Date() // 更新时间戳
      }
    });
    console.log(`[paySuccessCallback] 订单状态已更新为已支付，处理状态: ${targetStatus}，orderId=${orderId}`);

    let notifyOrderRequest = {orderId: orderId}
    try {
      console.log(`[paySuccessCallback] 通知员工处理订单: orderId=${orderId}`);
      await notifyOrderToStaff(notifyOrderRequest);
      console.log(`[paySuccessCallback] 通知员工成功: orderId=${orderId}`);
    } catch (err) {
      console.error('[paySuccessCallback] 通知员工失败:', err.message);
      console.error('Stack:', err.stack || '无堆栈信息');
    }

    // 返回成功结果
    console.log(`[paySuccessCallback] 处理完成: orderId=${orderId}`);
    return {
      code: 200,
      message: 'success',
      data: null
    };
  } catch (error) {
    console.error("[paySuccessCallback] Error:", error.stack || error);
    return {
      code: 500,
      message: "Error processing request",
      error: error.stack || error.message
    };
  }
}


// 更新优惠券状态
async function updateCouponStatus(coupon_record_id) {
  if (!coupon_record_id) {
    console.log('No couponId provided, skipping coupon update.');
    return;
  }

  // 查询优惠券记录
  const couponRecord = await db.collection('coupon_record').where({_id: coupon_record_id}).get();

  if (!couponRecord.data.length) {
    console.log('Coupon not found, skipping coupon update.');
    return;
  }

  // 更新优惠券状态
  await db.collection('coupon_record').where({_id: coupon_record_id}).update({
    data: {
      used_quantity: (couponRecord.data[0].used_quantity||0) + 1, // 更新已使用数量
      update_ts: new Date(), // 更新时间戳
    }
  });

  console.log(`Coupon [${coupon_record_id}] updated successfully.`);
}

// 更新砍价记录状态
async function updateBargainRecord(participantId) {
  if (!participantId) {
    console.log('No participantId provided, skipping bargain record update.');
    return;
  }

  // 查询并更新砍价记录
  const bargainRecord = await db.collection('bargain_record').where({
    participant_id: participantId
  }).get();

  if (!bargainRecord.data.length) {
    console.log('Bargain record not found, skipping update.');
    return;
  }

  await db.collection('bargain_record').where({
    participant_id: participantId
  }).update({
    data: {
      status: 'done', // 更新状态为完成
      update_ts: new Date() // 更新时间戳
    }
  });
  console.log(`Bargain record [${participantId}] updated successfully.`);
}

// 更新零食库存
async function updateSnackStock(snacksItems, schoolCode, buildingCode) {
  if (!snacksItems || snacksItems.length === 0) {
    console.log('No snacks items to update stock');
    return;
  }

  if (!schoolCode || !buildingCode) {
    console.error('Missing schoolCode or buildingCode for stock update');
    throw new Error('缺少学校代码或楼栋代码');
  }

  try {
    // 批量处理库存扣减
    const updatePromises = snacksItems.map(async (item) => {
      const { sub_product_id, count } = item;
      
      if (!sub_product_id || !count || count <= 0) {
        console.warn(`Invalid item data: sub_product_id=${sub_product_id}, count=${count}`);
        return;
      }

      try {
        // 查询当前库存（按学校+楼栋维度）
        const stockResult = await db.collection('snack_subproduct')
          .where({
            sub_product_id: sub_product_id,
            school_code: schoolCode,
            building_code: buildingCode
          })
          .get();

        if (stockResult.data.length === 0) {
          console.error(`Product not found: sub_product_id=${sub_product_id}, school_code=${schoolCode}, building_code=${buildingCode}`);
          throw new Error(`商品不存在: ${sub_product_id}, 学校: ${schoolCode}, 楼栋: ${buildingCode}`);
        }

        const currentStock = stockResult.data[0].stock;
        const newStock = currentStock - count;

        if (newStock < 0) {
          console.error(`Insufficient stock: sub_product_id=${sub_product_id}, current=${currentStock}, required=${count}, building=${buildingCode}`);
          throw new Error(`库存不足: ${sub_product_id}, 当前库存: ${currentStock}, 需要: ${count}, 楼栋: ${buildingCode}`);
        }

        // 更新库存（按学校+楼栋维度）
        await db.collection('snack_subproduct')
          .where({
            sub_product_id: sub_product_id,
            school_code: schoolCode,
            building_code: buildingCode
          })
          .update({
            data: {
              stock: newStock,
              update_ts: new Date()
            }
          });

        console.log(`Stock updated: ${sub_product_id}, ${currentStock} -> ${newStock}, building: ${buildingCode}`);
      } catch (err) {
        console.error(`Failed to update stock for ${sub_product_id}:`, err.message);
        throw err;
      }
    });

    // 等待所有库存更新完成
    await Promise.all(updatePromises);
    console.log(`All snack stock updates completed successfully for building: ${buildingCode}`);
  } catch (err) {
    console.error('updateSnackStock failed:', err.message);
    throw err;
  }
}

module.exports = {
  paySuccessCallback: paySuccessCallback,
  paoTuiPaySuccessCallback: paoTuiPaySuccessCallback
};